import React from "react";
// props: children, fallbackRender
type FallbackRender = (props: { error: Error | null }) => React.ReactElement;
export class ErrorBoundary extends React.Component<
  React.PropsWithChildren<{ fallbackRender: FallbackRender }>,
  { error: Error | null }
> {
  // 发生异常后 error为接收的的error而不是null
  state = { error: null };
  // 子组件发生错误 该方法被调用
  static getDerivedStateFromError(error: Error) {
    // error被赋值给state
    return { error };
  }
  render() {
    const { error } = this.state;
    const { fallbackRender, children } = this.props;
    if (error) {
      // 异常渲染
      return fallbackRender({ error });
    } else {
      // 正常渲染
      return children;
    }
  }
}
